package com.nisure.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.HttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.nisure.AutoKeywordApplication;
import com.nisure.common.CreateJsonObject;
import com.nisure.common.GetHttpJsonobject;
import com.nisure.common.R;
import com.nisure.entity.KeywordEntity;
import com.nisure.info.KeywordTypeInfo;
import com.nisure.service.KeywordService;
import com.nisure.type.AdgroupType;
import com.nisure.type.KeywordType;

@RestController
@RequestMapping("/keyword")
public class KeywordController {

	private static final Logger logger = LoggerFactory.getLogger(AutoKeywordApplication.class);
	@Autowired
	private GetHttpJsonobject getHttpJsonobject;
	@Autowired
	private KeywordService keywordService;
	@Autowired
	private CreateJsonObject createJsonObject;
	
	
	public JSONObject addKeyword(String accessToken,long adgroupId,List<String> keyword,List<Double> price){
		String url = "https://api.baidu.com/json/sms/v4/KeywordService/addWord";
		JSONObject paramsList = new JSONObject();
		List<JSONObject> jsonList = new ArrayList<JSONObject>();
		for (int i = 0; i < keyword.size(); i++) {
			JSONObject jsonParams = new JSONObject();
			jsonParams.put("keyword", keyword.get(i));
			jsonParams.put("adgroupId", adgroupId);
			jsonParams.put("price", price.get(i));
			jsonParams.put("pause", true);
			jsonList.add(jsonParams);
		}
		
		paramsList.put("keywordTypes", jsonList);
		JSONObject completeJson = createJsonObject.getJsonData(accessToken, paramsList);
		JSONObject responsejson = getHttpJsonobject.httpsRequest(url, "POST", completeJson.toJSONString());
		
		return responsejson;
		
	}
	public int saveKeyword(List<KeywordEntity> keywordEntity){
		return keywordService.saveKeyword(keywordEntity);
	}
	
	
	
	
	@RequestMapping("getUploadRecord")
	public R getUploadRecord(HttpServletRequest request){
		Map<String, Object> map = new HashMap<String, Object>();
		long userId = Long.valueOf(request.getSession().getAttribute("userId").toString());		
		map.put("userId", userId);
		List<KeywordEntity> keywordList = new ArrayList<KeywordEntity>();
		keywordList = keywordService.getKeywordRecord(map);	
		for (KeywordEntity keywordEntity : keywordList) {
			long statusCode = keywordEntity.getStatusCode();
			String statusDesc = "";
			if(statusCode == 0){
				statusDesc = "成功";
			}
			else if(statusCode == 901634) {
				statusDesc = "关键词最长为20个汉字或40个英文字符";
			} else if(statusCode == 901635){
				statusDesc = "关键词与已有的关键词冲突";
			} else if(statusCode == 901637) {
				statusDesc = "关键词中含有特殊字符";
			} else{
				statusDesc = "未知错误:" + statusCode;
			}
			keywordEntity.setStatusDesc(statusDesc);
		}
		return R.ok().put("keywordList", keywordList);		
	}
	
	public List<KeywordType> getAllKeyword(String accessToken,List<Long> adgroupId,long userId){
		String url = "https://api.baidu.com/json/sms/v4/KeywordService/getWord";
		String fields = "campaignId,adgroupId,keywordId,pcDestinationUrl,mobileDestinationUrl,"
				+ "phraseType,keyword,price,matchType,pause,status,wmatchprefer,pcQuality,pcScale,"
				+ "mobileQuality,mobileScale";
		String [] str = fields.split(",");
		List<String> list = Arrays.asList(str);
		//最多批量查询50个单元下的关键词;分批查询
		int index = adgroupId.size()/50;
		List<Long> adgroupIdList = new ArrayList<Long>();
		List<KeywordType> keywordTypeList = new ArrayList<KeywordType>();
		for(int i=0;i<=index;i++){
			if(i!=index){
				adgroupIdList = adgroupId.subList(i*50,(i+1)*50);
			}else{
				if(i*50==adgroupId.size()){
					continue;
				}
				adgroupIdList = adgroupId.subList(i*50,adgroupId.size());
			}

		JSONObject jsonParams = new JSONObject();
		jsonParams.put("wordFields", list);
		jsonParams.put("ids", adgroupIdList);
		jsonParams.put("idType", 5);
		JSONObject completeJson= createJsonObject.getJsonData(accessToken, jsonParams);
		JSONObject campaignjson = getHttpJsonobject.httpsRequest(url, "POST", JSONObject.toJSONString(completeJson, SerializerFeature.WriteMapNullValue));
		JSONObject bodyjson = JSONObject.parseObject(campaignjson.getString("body"));
		if(campaignjson.getString("body")==null){
			logger.info(campaignjson.toJSONString());
			return null;
		}
		if(JSONObject.parseArray(bodyjson.getString("data")).isEmpty()){
			logger.info(userId+"关键词数据为空");
			return null;
		}
		JSONArray array = JSONObject.parseArray(bodyjson.getString("data"));
		
		keywordTypeList.addAll(JSON.parseArray(array.toJSONString(),KeywordType.class));
		}
		return keywordTypeList;
	}
	
	public void getKeyword(String accessToken,long[] adgroupId){
		String url = "https://api.baidu.com/json/sms/v4/KeywordService/getWord";
		
		JSONObject jsonParam = new JSONObject();
		List<Long> adId = new ArrayList<Long>();
		for(long ad:adgroupId){
			adId.add(ad);
		}
		List<String> wordFieldsList = new ArrayList<String>();
		wordFieldsList.add("campaignId");
		wordFieldsList.add("adgroupId");
		wordFieldsList.add("keywordId");
		jsonParam.put("ids", adId);		
		jsonParam.put("idType", 11);
		jsonParam.put("wordFields", wordFieldsList);
		JSONObject completeJson = createJsonObject.getJsonData(accessToken, jsonParam);
		JSONObject responsejson = getHttpJsonobject.httpsRequest(url, "POST", completeJson.toJSONString());
		
	}
	public List<KeywordTypeInfo> saveAllKeyword(String accessToken,List<Long> adgroupId,long userId){
		List<KeywordTypeInfo> keywordTypeInfoList = new ArrayList<KeywordTypeInfo>();
		List<KeywordType> keywordTypeList = this.getAllKeyword(accessToken, adgroupId, userId);
		if(keywordTypeList!=null){
		for(KeywordType k : keywordTypeList){
			KeywordTypeInfo keywordTypeInfo = new KeywordTypeInfo();		
			BeanUtils.copyProperties(k,keywordTypeInfo);
			keywordTypeInfo.setPause(k.isPause()+"");			
			keywordTypeInfo.setUserId(userId);
			keywordTypeInfoList.add(keywordTypeInfo);
		}		
		int index = keywordTypeInfoList.size()/1000;
		for(int i=1;i<=index;i++){//每1000个执行一次批量插入
			keywordService.saveAllKeyword(keywordTypeInfoList.subList((i-1)*1000, i*1000));
		}
		if(keywordTypeInfoList.size()%1000>0){
			keywordService.saveAllKeyword(keywordTypeInfoList.subList(index*1000,keywordTypeInfoList.size()));
		}
		int result = keywordService.saveAllKeyword(keywordTypeInfoList);		
		if(result>0){			
			return keywordTypeInfoList;
		}
		}
		return null;
		
	}
}
